package heima.leadnews.app.gateway.filter;


import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//网关过滤器
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取response对象
        ServerHttpResponse response = exchange.getResponse();
        //从请求头中获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");


        //判断是否是登录 如果请求路径中包含/login 直接放行
        if (exchange.getRequest().getURI().getPath().contains("/login")) {
            //放行
            return chain.filter(exchange);
        }

        //判断token是否存在
        if (StringUtils.isEmpty(token)) {
            //如果token不存在 设置401响应码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2) {
                //过期了 设置401响应码返回响应
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }


    //决定当前过滤器的执行级别 数字越小,优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
